<?php 
// define('CAKE_MAIL_API_KEY', "*************************");
// define('CAKE_MAIL_USERNAME', "email@company.com");
// define('CAKE_MAIL_PASSWORD', "*******");
/*
 * CakeMail Class, by Olivier St-Laurent
 * 
 * Must define CAKE_MAIL_API_KEY, CAKE_MAIL_USERNAME, CAKE_MAIL_PASSWORD in config.php
 * 
 * Usage : 
    // Creating a Campaign
    $recipientlist = array(
        array('email' => 'ostlaurent@globalia.ca'), 
        array('email' => 'jgelineau@globalia.ca'), 
    );
    $cake = new CakeMail($errorMessage); // $errorMessage is an error message by reference
    $campaignID = $cake->createCampaign("Campaign Name", $errorMessage);
    $mailingID = $cake->createNewsletter($campaignID,"Campaign Name", "Subject", "Body", $recipientlist, "From Name", "replyto@email.com", "UNSUBSCRIBE URL", $errorMessage);
    if ($mailingID) {
        $cake->sendMailing($mailingID, $errorMessage);
    }
    // Check if $errorMessage is empty for success

    ////////////////
    // Getting Campaign Info as an Array
    $cake = new CakeMail();
    $campaignInfo = $cake->getCampaignStats(24); // 24 = Campaign ID
   
 */
class CakeMail {
    private $API_KEY  = CAKE_MAIL_API_KEY;
    private $USERNAME = CAKE_MAIL_USERNAME;
    private $PASSWORD = CAKE_MAIL_PASSWORD;
    
    function __construct(&$errorMessage=null) {
        $this->login($errorMessage);
    }
    function curl_cake($url,$data,&$errorMessage=null){
        if(empty($data['user_key']) && !empty($_SESSION['user_key']))$data['user_key']= $_SESSION['user_key'];
        if(empty($data['client_id']) && !empty($_SESSION['client_id']))$data['client_id']= $_SESSION['client_id'];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://api.wbsrvc.com/'.$url); 
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('apikey: '.$this->API_KEY));
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result= curl_exec($ch);
        if($result===false){
            $errorMessage= 'Curl error: '.curl_error($ch);
            $return= false;
        }else{
            $result= json_decode($result, true);
            if($result['status']=='success'){
                $return= $result['data'];
            }else{
                $errorMessage= $result['status'].". ".$result['data'];
                $return= false;
            }
        }
        curl_close($ch);
        return $return;
    }
    function login(&$errorMessage=null){
        if(!empty($_SESSION['user_key']))return $_SESSION['user_key'];
        if(($loginInfo= $this->curl_cake('User/login',array('email'=>$this->USERNAME,'password'=>$this->PASSWORD),$errorMessage))){
            $_SESSION['client_id']= $loginInfo['client_id'];
            return $_SESSION['user_key']= $loginInfo['user_key'];
        }
        return false;
    }
    function createCampaign($name,&$errorMessage=null){
        if($this->login($errorMessage))
            return $this->curl_cake('Campaign/Create',array('name'=>$name),$errorMessage);
        return false;
    }
    function getCampaignStats($campaignID,&$errorMessage=null){
        if($this->login($errorMessage))
            return $this->curl_cake('Campaign/GetInfo',array('campaign_id'=>$campaignID),$errorMessage);
        return false;
    }
    function createList($name,$from_name,$reply_to,$import=null,$unsubscribeUrl=null,&$errorMessage=null){
        if($this->login($errorMessage)){
            $listID= $this->curl_cake('List/Create',array('name'=>$name, 'sender_name'=>$from_name, 'sender_email'=>$reply_to, 'list_policy'=>'accepted'),$errorMessage);
            $this->curl_cake('List/SetInfo',array('list_id'=>$listID, 'goto_oo'=>$unsubscribeUrl),$errorMessage);
            if($listID && $import){
                if($this->curl_cake('List/Import',array('record'=>$import, 'list_id'=>$listID),$errorMessage)){
                    return $listID;
                }else{
                    return false;
                }
            }
            return $listID;
        }
        return false;
    }
    function createMailing($name,$campaignID, $setInfos=null, &$errorMessage=null){
        if($this->login($errorMessage)){
            $mailingID= $this->curl_cake('Mailing/Create',array('name'=>$name,'campaign_id'=>$campaignID, 'type'=>'standard', 'encoding'=>'utf-8', 'transfer_encoding'=>'base64'),$errorMessage);
            if(!empty($setInfos)){
                $setInfos['mailing_id']= $mailingID;
                if($this->curl_cake('Mailing/SetInfo',$setInfos,$errorMessage)){
                    return $mailingID;
                }else{
                    return false;
                }
            }
            return $mailingID;
        }
        return false;
    }
    function createNewsletter($campaignID, $name, $subject, $htmlBody, $recipientList, $from_name, $reply_to, $unsubscribeUrl=null, &$errorMessage=null){
        if(($listID= $this->createList($name,$from_name,$reply_to,$recipientList,$unsubscribeUrl,$errorMessage))){
            if(($mailingID= $this->createMailing($name, $campaignID, array(
                'list_id' => $listID,
                'subject' => $subject,
                'html_message' => $htmlBody,
                'reply_to' => $reply_to,
                'opening_stats' => 'true',
                'clickthru_html' => 'true',
            ), $errorMessage))){
                return $mailingID;
            }
        }
        return false;
    }
    function sendMailing($mailingID, &$errorMessage=null){
        if($this->login($errorMessage))
            return $this->curl_cake('Mailing/Schedule',array('mailing_id'=>$mailingID),$errorMessage);
        return false;
    }
    function getMailingInfo($mailingID, &$errorMessage=null){
        if($this->login($errorMessage))
            return $this->curl_cake('Mailing/GetInfo',array('mailing_id'=>$mailingID),$errorMessage);
        return false;
    }
}
